#include <webx/menu.h>
#include <webx/route.h>
#include <dbentity/T_XG_DBETC.h>

class EditDatabase : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(EditDatabase)

int EditDatabase::process()
{
	param_string(flag);
	param_string(type);
	param_string(name);
	param_string(host);
	param_string(port);
	param_string(user);
	param_string(step);
	param_string(stress);
	param_string(passwd);
	param_string(remark);
	param_string(enabled);
	param_string(charset);
	param_name_string(id);

	webx::CheckSystemRight(this);

	int res = 0;
	CT_XG_DBETC tab;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	tab.init(dbconn);
	tab.id = id;

	if (flag == "A" || flag == "U")
	{
		tab.host = host;
		tab.port = port;
		tab.user = user;
		tab.passwd = passwd;
		tab.charset = charset;

		if (type.length() > 0) tab.type = type;
		if (name.length() > 0) tab.name = name;
		if (step.length() > 0) tab.step = step;
		if (stress.length() > 0) tab.stress = stress;
		if (remark.length() > 0) tab.remark = remark;
		if (enabled.length() > 0) tab.enabled = enabled;

		tab.statetime.update();
		
		if (flag == "A")
		{
			res = tab.insert();
		}
		else
		{
			res = tab.update();

			typedef DBConnectPool* (*GetDBConnectPoolFunc)(const char*);

			static GetDBConnectPoolFunc getPool = (GetDBConnectPoolFunc)Process::GetObject("HTTP_GET_DBCONNECT_POOL");

			if (tab.find() && tab.next() && tab.enabled.val() > 0)
			{
				DBConnectPool* pool = getPool(id.c_str());

				if (pool)
				{
					ConfigFile cfg;
					string key = "DLLPATH_" + tab.type.val();
					string path = webx::GetParameter(stdx::toupper(key));

					if (path.empty())
					{
						path = stdx::tolower(tab.type.val());
						path = stdx::translate("$PRODUCT_HOME/dll/libdbx." + path + "pool.so");
					}

					cfg.setVariable("DLLPATH", path);
					cfg.setVariable("HOST", tab.host.val());
					cfg.setVariable("USER", tab.user.val());
					cfg.setVariable("NAME", tab.name.val());
					cfg.setVariable("PORT", (int)tab.port.val());
					cfg.setVariable("CHARSET", tab.charset.val());
					cfg.setVariable("PASSWORD", tab.passwd.val());

					pool->init(cfg);
				}

				webx::ReloadSystemConfig();
			}
		}
	}
	else if (flag == "D")
	{
		if (!tab.find())
		{
			res = XG_SYSERR;
		}
		else if (tab.next())
		{
			res = tab.remove();
		}
		else
		{
			res = XG_NOTFOUND;
		}
	}
	else
	{
		res = XG_PARAMERR;
	}

	json["code"] = res;
	out << json;
	
	return XG_OK;
}